package com.gl.service.impl;

import com.gl.mapper.FileMapper;
import com.gl.pojo.entity.File;
import com.gl.service.FileService;
import com.gl.utils.AliyunOSSOperator;
import com.gl.utils.CurrentHolder;
import com.gl.utils.UuidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class FileServiceImpl implements FileService {
    @Autowired
    private FileMapper fileMapper;
    @Autowired
    private AliyunOSSOperator aliyunOSSOperator;

    /**
     * 根据会议id和用户id获取文件信息
     * @param meetingId 会议ID
     * @param userId 用户ID
     * @return -
     */
    public File getFileInfoByMeetingIdAndUserId(String meetingId, String userId){
        if (meetingId == null || userId == null) return null;
        return fileMapper.getFileInfoByMeetingIdAndUserId(meetingId, userId);
    }

    /**
     * 上传文件
     * @param meetingId 会议ID
     * @param multipartFile 文件
     */
    @Override
    public void uploadFile(String meetingId, MultipartFile multipartFile) {
        if (multipartFile == null)return;
        // 获取用户id
        String userId = CurrentHolder.getCurrentId();
        // 获取文件名
        String fileName = multipartFile.getOriginalFilename();
        // 获取文件类型
        String fileType = multipartFile.getContentType();
        // 生成文件id
        String fileId = UuidUtils.getUuid();
        // 上传文件
        String fileUrl;
        try {
            // 获取文件的地址url
            fileUrl = aliyunOSSOperator.upload(multipartFile.getBytes(), fileName);
        }catch (Exception e){
            throw new RuntimeException("上传文件失败！");
        }
        // 文件保存
        File file = new File();
        file.setId(fileId);
        file.setName(fileName);
        file.setType(fileType);
        file.setUrl(fileUrl);
        file.setUserId(userId);
        file.setMeetingId(meetingId);
        fileMapper.insertFile(file);
    }
}
